package es.truscoandrisco.discotecasmadrid;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.curso.android.SocialConnector.Facebook.BaseRequestListener;
import com.curso.android.SocialConnector.Facebook.SessionEvents;
import com.curso.android.Utils.SDKFacebook.AsyncFacebookRunner;
import com.curso.android.Utils.SDKFacebook.DialogError;
import com.curso.android.Utils.SDKFacebook.Facebook;
import com.curso.android.Utils.SDKFacebook.FacebookError;
import com.curso.android.Utils.SDKFacebook.Facebook.DialogListener;


public class Lista extends ListActivity{

	private static ArrayList<Discoteca> arrayDisco = new ArrayList<Discoteca>();
	static Drawable[] arrayLogos = new Drawable[200];
	static boolean visitedLogos[] = new boolean[200];
	public static MyAdapter mAdapter = null;
	public static View localView;
	private static String URL_MY_STATUS = "me/feed/";
	final Facebook mFacebook = new Facebook("17...");
	private Activity mActivity;
	private String tipo, clase;
	private Context mContext;
	
	
	@Override
    public void onCreate(Bundle savedInstanceState){
        
        super.onCreate(savedInstanceState);
        
        mContext = getApplicationContext();
        
        new getImageTask().execute();
        mActivity = this;
        
        mAdapter = new MyAdapter(this);
		setListAdapter(mAdapter);
		
		registerForContextMenu(getListView());
     
	}

//////////////////////////////////////////////////////////////////////////////////////////////////////
	
	 protected void onListItemClick(ListView l, View v, int position, long id){
		 	
		 	final int pos = position-1;
		 	
			if (arrayDisco.get(position-1).getPremium().equals("si")) {
			    Intent i = new Intent(this, DiscoActivity.class);
				
				i.putExtra("DESCRIPCION", arrayDisco.get(pos).getDescripcion());
				i.putExtra("EVENTO1", arrayDisco.get(pos).getEvento1());
				i.putExtra("EVENTO2", arrayDisco.get(pos).getEvento2());
				i.putExtra("NOMBRE", arrayDisco.get(pos).getNombre());
				i.putExtra("DIRECCION", arrayDisco.get(pos).getDireccion());
				i.putExtra("LATITUD", arrayDisco.get(pos).getLatitud());
				i.putExtra("LONGITUD", arrayDisco.get(pos).getLongitud());
	
				startActivity(i);
			} else {
				final CharSequence[] items = {"Ver mapa", "Publicar en Facebook"};

				AlertDialog.Builder builder = new AlertDialog.Builder(Lista.this);
				builder.setTitle("Selecciona la opción: ");
				builder.setItems(items, new DialogInterface.OnClickListener() {		
					public void onClick(DialogInterface dialog, int item) {
						if (item == 0){
						    Intent i = new Intent(mContext, mapas.class);
							i.putExtra("LATITUD", arrayDisco.get(pos).getLatitud());
							i.putExtra("LONGITUD", arrayDisco.get(pos).getLongitud());
						    i.putExtra("NOMBRE", arrayDisco.get(pos).getNombre());
							startActivity(i);

						}else{
							String [] permissions = new String[2];
					       	permissions[0] = "publish_stream";
					       	permissions[1] = "read_stream";	
					        String nombre = arrayDisco.get(pos).getNombre();
							final CharSequence item1 = "Estoy pensando en ir a " + nombre + " esta noche...";
							final CharSequence item2 = "Esta noche voy a ir a " + nombre;
							final CharSequence item3 = "Estoy yendo a " + nombre;
							final CharSequence item4 = "Estoy en " + nombre;
							
							final CharSequence[] items = {item1, item2, item3, item4};

							AlertDialog.Builder builder = new AlertDialog.Builder(Lista.this);
							builder.setTitle("Selecciona el mensaje: ");
							builder.setItems(items, new DialogInterface.OnClickListener() {
								
							public void onClick(DialogInterface dialog, int item) {

					        	String status = (String) items[item];
					        		
							    if (updateStatus(status))
							        Toast.makeText(getApplicationContext(), "Mensaje publicado correctamente",
							        		Toast.LENGTH_SHORT).show();
							    else
								    Toast.makeText(getApplicationContext(), "El mensaje no ha podido ser publicado",
								        	Toast.LENGTH_SHORT).show();
							    }
							});
							
							AlertDialog alert = builder.create();
							alert.show();
							
							if (!mFacebook.isSessionValid())
								mFacebook.authorize(mActivity, permissions, new LoginDialogListener());
						    }
						}
					});
				
				AlertDialog alert = builder.create();
				alert.show();
			}
	 }		
	 
//////////////////////////////////////////////////////////////////////////////////////////////////////

	 
	public void filtrar(){
		
		final CharSequence[] items = {"Zona", "Música", "Lista completa"};
		final CharSequence[] itemsMusica = {"House", "Rock", "Pachangueo", "Pop", "HipHop", "Flamenco", "Varias", "Otras"};
		final CharSequence[] itemsZona = {"Sol", "TorreEuropa", "Moncloa", "Atocha", "AlonsoMartínez",
								"PuertaToledo", "Serrano", "NuevosMinisterios", "Cuzco"};

		AlertDialog.Builder filtroZona = new AlertDialog.Builder(this);
		filtroZona.setTitle("Seleccione zona:");
		
		AlertDialog.Builder filtroMusica = new AlertDialog.Builder(this);
		filtroMusica.setTitle("Seleccione música:");
		
		filtroMusica.setItems(itemsMusica, new DialogInterface.OnClickListener(){
		    public void onClick(DialogInterface dialog, int item){
		        tipo = "musica";
		        clase = (String) itemsMusica[item];
		        new getListaFiltrada().execute();
		    }
		});
		
		filtroZona.setItems(itemsZona, new DialogInterface.OnClickListener(){
		    public void onClick(DialogInterface dialog, int item){
		        tipo = "zona";
		        clase = (String) itemsZona[item];
		        new getListaFiltrada().execute();     
		    }
		});
		
		final AlertDialog zona = filtroZona.create();
		final AlertDialog musica = filtroMusica.create();
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Seleccione un filtro:");
		
		builder.setItems(items, new DialogInterface.OnClickListener(){
		    public void onClick(DialogInterface dialog, int item){
		        if (items[item].equals("Zona"))
		        	zona.show();
		        else
			        if (items[item].equals("Música"))
			        	musica.show();
			        else
			        	refreshList();
		    }
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

//////////////////////////////////////////////////////////////////////////////////////////////////////
	
	public class MyAdapter extends BaseAdapter {
        
		private Context mContext;
		private ViewGroup thisParent;
		
		
		public MyAdapter(Context c) {		
			mContext = c;
		}

		public int getCount() {
			return arrayDisco.size()+1;
		}
		
		public Object getItem(int position){
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			
			View view;
			LayoutInflater inflater;
			
			if (position == 0){
				inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = inflater.inflate(R.layout.myfirstitem, null);
				Button act = (Button) view.findViewById(R.id.act);
				act.setText("Filtrar");
				
				act.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						filtrar();
					}
				});
				
			}else{
					inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					view = inflater.inflate(R.layout.myitem, null);
				
				ImageView imgv = (ImageView) view.findViewById(R.id.image);
				
				if (visitedLogos[position-1] == false) {
					launchDownloadIcon(position-1);
					visitedLogos[position-1] = true;
				}else{
					imgv.setImageDrawable(arrayLogos[position-1]);
				}	

				TextView t = (TextView) view.findViewById(R.id.title);
				t.setText(arrayDisco.get(position-1).getNombre());
				
				ImageView premium = (ImageView) view.findViewById(R.id.premium);
				if (arrayDisco.get(position-1).getPremium().equals("si")){
					premium.setImageDrawable(mContext.getResources().getDrawable(R.drawable.premium));
				}else
					premium.setImageDrawable(null);
				
				t = (TextView) view.findViewById(R.id.evento);
				t.setText(arrayDisco.get(position-1).getDireccion());
				
				t = (TextView) view.findViewById(R.id.zona);
				t.setText(arrayDisco.get(position-1).getLogo());
				
				t = (TextView) view.findViewById(R.id.musica);
				t.setText(arrayDisco.get(position-1).getImagen());
			}
			
			return view;
	
		}
		
		public Context getContext(){
			return mContext;
		}
		
		public ViewGroup getParent (){
			return thisParent;
		}
	}
	
//////////////////////////////////////////////////////////////////////////////////////////////////////
	
	
	private class getImageTask extends AsyncTask<Void, Void, Void>{
		
		ProgressDialog pd;
		
		protected void onPreExecute(){
			pd = ProgressDialog.show(Lista.this, "Por favor espere...", "Cargando lista de discotecas...", true);	
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			MyJSONParser mjp = new MyJSONParser();
	        String str = mjp.doGet("http://...");
	        arrayDisco = mjp.parse(str);
	        
	        for (int i = 0; i < arrayDisco.size(); i++){
	        	visitedLogos[i] = false;
	        }
		
			return null; 
		}
		
		protected void onPostExecute(Void unused){
			if (!isFinishing()){
				pd.dismiss();
				mAdapter.notifyDataSetChanged();
			}
		}
	
	}
	
	
//////////////////////////////////////////////////////////////////////////////////////////////////////
	
	private class getListaFiltrada extends AsyncTask<Void, Void, Void>{
		
		ProgressDialog pd;
		
		protected void onPreExecute(){
			pd = ProgressDialog.show(Lista.this, "Por favor espere...", "Cargando lista de discotecas...", true);	
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			MyJSONParser mjp = new MyJSONParser();
			arrayDisco = new ArrayList<Discoteca>();
	        String str = mjp.doGet("http://..."+ tipo + "/" + clase);
	        arrayDisco = mjp.parse(str);
	        
	        for (int i = 0; i < arrayDisco.size(); i++){
	        	visitedLogos[i] = false;
	        }
		
			return null; 
		}
		
		protected void onPostExecute(Void unused){
			if (!isFinishing()){
				pd.dismiss();
				mAdapter.notifyDataSetChanged();
				if (arrayDisco.size() == 0)
					Toast.makeText(getApplicationContext(), "No se han encontrado resultados", Toast.LENGTH_SHORT).show();
			}
		}
	}
	
//////////////////////////////////////////////////////////////////////////////////////////////////////
	
	public static void launchDownloadIcon(int position) {
		new downloadIcon().execute(position);
	}
	
	private static class downloadIcon extends AsyncTask<Integer, Void, Void> {

		@Override
		protected Void doInBackground(Integer... params) {
			Integer position = params[0];
			
			if ((arrayDisco != null) && (arrayDisco.size() > position)){ 	

				String url = "http://..." + arrayDisco.get(position).getNombre() + "...jpg";
				
				try {
					arrayLogos[position] = arrayDisco.get(position).setImagenImg(url, "");
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			return null;
		}
		
		protected void onPostExecute(Void unused) {			
			mAdapter.notifyDataSetChanged();
		}    
	
	}
	
	
//////////////////////////////////////////////////////////////////////////////////////////////////////

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.Actualizar:
        	refreshList();
            return true;
        case R.id.about:
        	Intent i = new Intent(this, About.class);
        	startActivity(i);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    
//////////////////////////////////////////////////////////////////////////////////////////////////////
  
	public void refreshList() {
        
		//for (int i = 0; i < 200; i++){
        	//visitedLogos[i] = false;
        //}
        
		new getImageTask().execute();
			
		mAdapter = new MyAdapter(this);
		setListAdapter(mAdapter);
		
	}
	
	
//////////////////////////////////////////////////////////////////////////////////////////////////////
	
	private final class LoginDialogListener implements DialogListener {
        public void onComplete(Bundle values) {
            SessionEvents.onLoginSuccess();
            // 0 -> session doesn't expire.
            mFacebook.setAccessExpires(0);
        }

        public void onFacebookError(FacebookError error) {
            SessionEvents.onLoginError(error.getMessage());
        }
        
        public void onError(DialogError error) {
            SessionEvents.onLoginError(error.getMessage());
        }

        public void onCancel() {
            SessionEvents.onLoginError("Action Canceled");
        }
    }
	
	private boolean updateStatus(String newStatus){
		if (!mFacebook.isSessionValid() || newStatus.trim().equals("")) {	
			return false;
		}else{			
			Bundle bundle = new Bundle();
			bundle.putString("message", newStatus.trim());
			try{
				AsyncFacebookRunner async = new AsyncFacebookRunner(mFacebook);
				async.request(URL_MY_STATUS, bundle, "POST", new UpdateMyStatusListener());
			}catch(Exception ex){
				return false;
			}
		}
		return true;
	}
	
	public class UpdateMyStatusListener extends BaseRequestListener {
        public void onComplete(final String response) {
        }
    }
	
}
